import 'package:bilibili/navigator/hi_navigator.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:dots_indicator/dots_indicator.dart';
import 'package:flutter/material.dart';
import 'package:hi_common/util/logger.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:visibility_detector/visibility_detector.dart';

import '../const/Const.dart';
import '../http/model/banner_mo.dart';

typedef OnBannerClick = Function();

class HiBanner extends StatefulWidget {
  final List<BannerMo> items;
  final double bannerHeight;

  const HiBanner(this.items, {super.key, this.bannerHeight = 160});

  @override
  State<StatefulWidget> createState() {
    return _HiBannerState();
  }
}

class _HiBannerState extends State<HiBanner> {
  int pageIndex = 0;
  late ValueNotifier<bool> autoPlayNotifier;

  @override
  void initState() {
    super.initState();
    autoPlayNotifier = ValueNotifier<bool>(true);
  }

  @override
  void dispose() {
    autoPlayNotifier.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: widget.bannerHeight,
      child: Stack(
        children: [
          ValueListenableBuilder<bool>(
              valueListenable: autoPlayNotifier,
              builder: (context, autoPlay, _) {
                return _buildCarouselSlider(autoPlay: autoPlay);
              }),
          Align(
            alignment: Alignment.bottomRight,
            child: Padding(
              padding: const EdgeInsets.only(bottom: 5, right: 5),
              child: _buildDotsIndicator(),
            ),
          ),
          _detector(child: Container(), key: GlobalKey())
        ],
      ),
    );
  }

  Widget _buildCarouselSlider({bool autoPlay = false}) {
    return ClipRRect(
      borderRadius: const BorderRadius.all(Radius.circular(6)),
      child: CarouselSlider(
        options: CarouselOptions(
            height: widget.bannerHeight,
            autoPlay: autoPlay,
            viewportFraction: 1.0,
            onPageChanged: (int index, CarouselPageChangedReason reason) {
              setState(() {
                pageIndex = index;
              });
            }),
        items: widget.items.map((model) {
          return InkWell(
            onTap: () {
              _onClickBanner(model);
            },
            child: _image(model.cover),
          );
        }).toList(),
      ),
    );
  }

  _detector({required Widget child, required Key key}) {
    return VisibilityDetector(
      onVisibilityChanged: (VisibilityInfo info) {
        var visiblePercentage = info.visibleFraction * 100;
        logger.i("hiBanner visibility : $visiblePercentage");
        bool newAutoPlay = visiblePercentage >= 50; // 调整阈值以适应需求
        if (newAutoPlay != autoPlayNotifier.value) {
          autoPlayNotifier.value = newAutoPlay;
        }
      },
      key: key,
      child: child,
    );
  }

  Widget _buildDotsIndicator() {
    return DotsIndicator(
      dotsCount: widget.items.length,
      position: pageIndex,
      decorator: const DotsDecorator(
          color: Colors.white60,
          activeColor: Colors.white,
          size: Size.square(6.0),
          activeSize: Size.square(6.0),
          spacing: EdgeInsets.only(top: 6, bottom: 6, left: 3, right: 3)),
    );
  }

  Widget _image(String uri) {
    return Container(
        height: double.infinity,
        width: double.infinity,
        color: Colors.green,
        child: Image.network(
          uri,
          fit: BoxFit.cover,
        ));
  }

  _onClickBanner(BannerMo model) {
    if (model.type == "video") {
      HiNavigator.getInstance()
          .onJumpTo(RouteStatus.detail, args: {Const.VIDEO_ID: model.url});
    } else {
      launchUrl(Uri.parse(model.url));
    }
  }
}
